package org.openharmony.qttool;

import com.intellij.openapi.actionSystem.ActionUpdateThread;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import org.jetbrains.annotations.NotNull;

public class EditUIAction extends AnAction {

    @Override
    public @NotNull ActionUpdateThread getActionUpdateThread() {
        return super.getActionUpdateThread();
    }

    @Override
    public void actionPerformed(@NotNull AnActionEvent event) {
        // TODO: insert action logic here
        Project project = event.getProject();
        if (project == null) {
            Messages.showErrorDialog("Cannot get Qt SDK info", "Error");
            return;
        }

        QtSDK sdk = project.getUserData(Utils.qtSDKKey());
        if (sdk == null || !sdk.isValid()) {
            Messages.showErrorDialog("Cannot get Qt SDK info", "Error");
            return;
        }
        String designer = sdk.designer();
        if (designer == null) {
            Messages.showErrorDialog("Cannot get designer tool", "Error");
            return;
        }
        try {
//            获取当前选中的ui文件
            VirtualFile virtualFile = event.getData(CommonDataKeys.VIRTUAL_FILE);
//            使用designer打开ui文件
            if (virtualFile != null) {
                ProcessBuilder pb = new ProcessBuilder(designer, virtualFile.getPresentableUrl());
                pb.start();
            }
        } catch (Exception e) {
            Utils.handleException(e);
        }
    }


    /**
     *  ÓÃÀ´¶¯Ì¬¸üÐÂ¶¯×÷µÄ×´Ì¬ºÍÍâ¹Û£¬µÄÈ·±£Ñ¡ÖÐuiÎÄ¼þ²ÅÏÔÊ¾°´Å¥
     */
    @Override
    public void update(@NotNull AnActionEvent event) {
//        È·±£¸¸ÀàÖÐ¶¨ÒåµÄ¸üÐÂÂß¼­±»Ö´ÐÐ
        super.update(event);
        try {
            VirtualFile virtualFile = event.getData(CommonDataKeys.VIRTUAL_FILE);
            event.getPresentation().setEnabledAndVisible(virtualFile != null &&
                    !virtualFile.isDirectory() &&
                    getFileSuffix(virtualFile.getPresentableUrl()).equals("ui"));
        } catch (Exception e) {
            Utils.handleException(e);
        }
//        ÉèÖÃ¶¯×÷µÄÏÔÊ¾ÎÄ±¾ÎªOpen UI
        event.getPresentation().setText("Open UI");
    }


    private String getFileSuffix(String fileName) {
        if (fileName.isEmpty()) {
            return "";
        }
        int dotIndex = fileName.lastIndexOf(".");
        return dotIndex == -1 ? "" : fileName.substring(dotIndex + 1);
    }
}
